﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Clover.Auth.Permission
{
    public class PermissionProviderCollection : Collection<IPermissionProvider>
    {
        private IPermission[] _permissions;

        public IPermission[] Permissions {
            get {
                if (_permissions == null) {
                    _permissions = GetPermissions();
                }
                return _permissions;
            }
        }

        public PermissionProviderCollection () {}

        public PermissionProviderCollection(IList<IPermissionProvider> _permissionProviders) :base(_permissionProviders) { }

        internal virtual IPermission[] GetPermissions() {
            return Items.Select(m => m.GetPermissions())
                        .Aggregate((m, n) => m.Concat(n))
                        .ToArray();
        }

        protected override void ClearItems()
        {
            _permissions = null;
            base.ClearItems();
        }

        protected override void InsertItem(int index, IPermissionProvider item)
        {
            _permissions = null;
            base.InsertItem(index, item);
        }

        protected override void RemoveItem(int index)
        {
            _permissions = null;
            base.RemoveItem(index);
        }

        protected override void SetItem(int index, IPermissionProvider item)
        {
            _permissions = null;
            base.SetItem(index, item);
        }
    }
}
